package save_http_picture

import (
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"os"
	"strconv"
	"time"
)

//写入文件
func SaveJokeFile(url string) {
	//保存图片的名字是随机的6个数字
	rand.Seed(time.Now().UnixNano())
	var captcha string
	for i := 0; i < 6; i++ {
		//产生0到9的整数
		num := rand.Intn(10)
		//将整数转为字符串
		captcha += strconv.Itoa(num)
	}

	//保存在本地的地址
	path := "C:/Users/wangk/Desktop/go_auto/tmp" + captcha + ".jpg"
	f, err := os.Create(path)
	if err != nil {
		fmt.Println("HttpGet err:", err)
		return
	}
	defer f.Close()

	//读取url的信息
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("http err:", err)
		return
	}
	defer f.Close()

	buf := make([]byte, 4096)
	for {
		n, err2 := resp.Body.Read(buf)
		if n == 0 {
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}
		//写入文件
		f.Write(buf[:n])
	}

}

func SpidePage(page_urls ...string) {

	for i := 0; i < len(page_urls); i++ {
		SaveJokeFile(page_urls[i])

	}
}
